package com.cavy.platform.server.controller;

import com.cavy.platform.server.BeansProvider;
import com.cavy.platform.server.service.JobSubscribe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

/**
 * job事件订阅处理
 */
@ServerEndpoint("/job/{workSpace}/{project}/{pipeline}/{number}")
@Component
@Slf4j
public class JobSubscribeHandler {

    @Autowired
    private JobSubscribe service = BeansProvider.getBean(JobSubscribe.class);

    @OnOpen
    public void onOpen(Session session, @PathParam("workSpace") String workSpace, @PathParam("project") String project,
                       @PathParam("pipeline") String pipeline, @PathParam("number") String number) {
        log.debug("open session:{},workSpace:{},project:{},pipeline:{},number:{}", session, workSpace, project, pipeline, number);
        service.subscribe(session, workSpace, project, pipeline, number);
    }

    @OnClose
    public void onClose(Session session, @PathParam("workSpace") String workSpace, @PathParam("project") String project,
                        @PathParam("pipeline") String pipeline, @PathParam("number") String number) {
        log.debug("onClose session:{},workSpace:{},project:{},pipeline:{},number:{}", session, workSpace, project, pipeline, number);
        service.unSubscribe(session, workSpace, project, pipeline, number);
    }

    @OnMessage
    public void onMessage(String message, Session session, @PathParam("workSpace") String workSpace, @PathParam("project") String project,
                          @PathParam("pipeline") String pipeline, @PathParam("number") String number) {
        log.debug("onMessage session:{},workSpace:{},project:{},pipeline:{},number:{}", session, workSpace, project, pipeline, number);
        service.onMessage(session, message, workSpace, project, pipeline, number);
    }

    @OnError
    public void onError(Session session, Throwable error, @PathParam("workSpace") String workSpace, @PathParam("project") String project,
                        @PathParam("pipeline") String pipeline, @PathParam("number") String number) {
        log.debug("onError session:{},workSpace:{},project:{},pipeline:{},number:{}", session, workSpace, project, pipeline, number);
        log.warn(error.getMessage());
        onClose(session, workSpace, project, pipeline, number);
    }
}
